package Demo01;
import java.lang.ref.Cleaner;
class DatabaseConnection implements Runnable{
    public DatabaseConnection(){
       System.out.println("连接已打开");
    }
    @Override
    public void run() {
        System.out.println("连接已关闭");
    }
}

class ConnectionManager implements AutoCloseable{
    public static final Cleaner cleaner = Cleaner.create();
    private Cleaner.Cleanable cleanable;
    public ConnectionManager(DatabaseConnection databaseConnection){
        this.cleanable = cleaner.register(this,databaseConnection);
    }
    public  void databaseOperation(){
       System.out.println("正在执行操作...");
    }
    @Override
    public void close() throws Exception {
        this.cleanable.clean();
    }
}
public class Cleaner07 {
    public static void main(String[] args) throws Exception{
        DatabaseConnection databaseConnection = new DatabaseConnection();
        try (ConnectionManager manager = new ConnectionManager(databaseConnection)){
        manager.databaseOperation();
        } catch(Exception e) {}
    }
}
